﻿using System;


namespace BasicallyNot.CodeTransformers.Searchers
{

	internal class ContainsValueNotExit : IVisualSearcher
	{

		void IVisualSearcher.Match( VisualSearcherEventArg arg, ref VisualSearchResult result )
		{
			result.IsMatch = false;

			int start = arg.LineText.IndexOf( arg.Keyword );
			if ( start < 0 )
				return;

			if ( start > 0 ) {
				char justBefore = arg.LineText[ start - 1 ];
				if ( char.IsLetterOrDigit( justBefore ) )
					return;
			}

			int justAfterIndex = start + arg.Keyword.Length;
			if ( justAfterIndex < arg.LineText.Length ) {
				char justAfter = arg.LineText[ justAfterIndex ];
				if ( char.IsLetterOrDigit( justAfter ) )
					return;
			}

			// make sure we're not inside a string value or a comment
			for ( int i = 0; i < start; ++i ) {
				char c = arg.LineText[ i ];
				if ( c == '"' || c == '\'' )
					return;

				// is the current character an 'e' and is there room for "exit " before we reach the actual keyword?
				if ( (c == 'e' || c == 'E') && i + 4 < start) {
					string exit = arg.LineText.Substring( i, 4 );
					if ( "exit".Equals( exit, StringComparison.CurrentCultureIgnoreCase ) )
						return;
				}
			}

			result.MatchIndex = start;
			result.IsMatch = true;
		}

	}

}
